<template>
    <template v-for="(item, index) in options" :key="index">
        <Cell @click="toggle(index)">
            <template #title v-if="canCheckedAll || !item[childrenLabel]">
                <div style="display: flex;">
                    <Checkbox style="margin-left: 8px;" :name="item[valueLabel]"
                        :ref="(el: any) => checkboxRefs[index] = el" @click.stop />
                    <span style="margin-left: 8px;">{{ item[textLabel] }}</span>
                </div>
            </template>
        </Cell>
        <div style="padding-left: 20px;" v-if="item[childrenLabel]">
            <cell_item :canCheckedAll="canCheckedAll" :options="item[childrenLabel]"
                :ref="(el: any) => cellItemRefs[index] = el" :columns-names="columnsNames"></cell_item>
        </div>
    </template>
</template>
<script setup lang="ts">
import { Checkbox, Cell, type CheckboxInstance } from "vant";
import { ref, type Ref, onBeforeUpdate, computed } from "vue";
interface prop {
    options: Record<string, any>[]
    columnsNames?: { text: string, value: string, children: string }
    canCheckedAll?: boolean
}

const { options, columnsNames = { text: 'text', value: 'value', children: 'children' }, canCheckedAll } = defineProps<prop>()
const checkboxRefs: Ref<CheckboxInstance[]> = ref([]);
const cellItemRefs: Ref<number[]> = ref([]);
const valueLabel = computed(() => columnsNames.value || 'value')
const textLabel = computed(() => columnsNames.text || 'text')
const childrenLabel = computed(() => columnsNames.children || 'children')

const toggle = (index: number) => {
    checkboxRefs.value[index]?.toggle();
};
onBeforeUpdate(() => {
    checkboxRefs.value = [];
});
</script>